package com.platform.api.bzproject.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.platform.api.bzproject.dao.BzTalentMapper;
import com.platform.api.bzproject.dao.UserMapper;
import com.platform.api.bzproject.model.BzConfig;
import com.platform.api.bzproject.model.BzTalent;
import com.platform.api.bzproject.model.User;
import com.platform.api.bzproject.service.BzConfigService;
import com.platform.api.bzproject.service.IBzTalentService;
import com.platform.api.bzproject.service.UserService;
import com.platform.api.bzproject.vo.TalentVo;
import com.platform.common.core.Constant;
import com.platform.common.util.EncryptionUtil;
import com.platform.security.dao.AppConnectMapper;
import com.platform.security.enums.App;
import com.platform.security.model.AppConnect;
import com.platform.security.service.AppConnectService;
import com.platform.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 达人注册表 服务实现类
 * </p>
 *
 * @author guoshao
 * @since 2021-10-22
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class BzTalentServiceImpl extends ServiceImpl<BzTalentMapper, BzTalent> implements IBzTalentService {


    @Autowired
    private BzTalentMapper bzTalentMapper;

    @Autowired
    private BzConfigService bzConfigService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AppConnectMapper appConnectMapper;


    public List<Map<String, Object>> selectLimitBzTalent() {
        List<Map<String, Object>> maps = bzTalentMapper.selectLimitBzTalent();
        if(maps.size() > 5){
            Map<String, Object> map = new HashMap<>();
            BzConfig more = bzConfigService.getByType("more");
            map.put("userid",0);
            map.put("avatar_url",more.getValue());
            maps.add(map);
        }
        return maps;
    }

    @Override
    public PageInfo<TalentVo> selectBzTalentList(TalentVo talentVo, Integer offset) {

        Integer pageNum = 1;
        if(offset > 0){
            pageNum = (offset / Constant.DAREN_PAGESIZE) + 1;
        }

        PageHelper.startPage(pageNum, Constant.DAREN_PAGESIZE);

        PageInfo<TalentVo> pageInfo = new PageInfo<>(bzTalentMapper.selectBzTalentList(talentVo));
        return pageInfo;
    }

    /**
     * 获取我的邀请记录
     * @param offset
     * @return
     */
    @Override
    public PageInfo<TalentVo> selectInvitationRecord(Map<String,Object> map,Integer offset){

        Integer pageNum = 1;
        if(offset > 0){
            pageNum = (offset / Constant.DAREN_PAGESIZE) + 1;
        }

        PageHelper.startPage(pageNum, Constant.DAREN_PAGESIZE);

        PageInfo<TalentVo> pageInfo = new PageInfo<>(bzTalentMapper.selectInvitationRecord(map));
        return pageInfo;
    }

    /**
     * 获取我的邀请记录
     * @param offset
     * @return
     */
    @Override
    public PageInfo<TalentVo> apprevoList(Map<String,Object> map,Integer offset){

        Integer pageNum = 1;
        if(offset > 0){
            pageNum = (offset / Constant.DAREN_PAGESIZE) + 1;
        }

        PageHelper.startPage(pageNum, Constant.DAREN_PAGESIZE);

        PageInfo<TalentVo> pageInfo = new PageInfo<>(bzTalentMapper.apprevoList(map));
        return pageInfo;
    }

    @Override
    public int updateRecommenderWord(String word,String recommenderWord) {
        return bzTalentMapper.updateRecommenderWord(word,recommenderWord);
    }

    @Override
    public void adduserInfo(BzTalent talent) {

        String userId_ = SecurityUtils.getUser().getUserId();
        //获取当前用户小程序信息
        AppConnect connect = appConnectMapper.getByUserId(userId_, Integer.valueOf(talent.getMiniType()));
        talent.setOpenid(null != connect ? connect.getOpenid(): null);

        Date now = new Date();
        talent.setRegTime(now);
        talent.setUpdateTime(now);
        talent.setStatus(1);
        talent.setPic(talent.getAvatarUrl());

        AppConnect appConnect = null;

        appConnect = appConnectMapper.getByBizUserId(talent.getOpenid(), Integer.valueOf(talent.getMiniType()));

        //绑定其关系
        String connectUserId = appConnect.getUserId();
        talent.setUserid(connectUserId);

        User userEntity = userMapper.getUserByBizUserId(Integer.valueOf(talent.getMiniType()), talent.getOpenid());

        boolean isExists = true;

        if(null == userEntity){
            userEntity = new User();
            isExists = false;
        }

        userEntity.setUserMobile(talent.getPhone());
        userEntity.setNickName(talent.getNickname());
        userEntity.setPic(talent.getPic());
        userEntity.setStatus(1);
        userEntity.setModifyTime(now);
        //设置密码
        String password = EncryptionUtil.combinationEncryp( Constant.PASSWORD);
        userEntity.setLoginPassword(password);

        if(isExists){
            userMapper.updateById(userEntity);
        }else{
            userEntity.setUserId(connectUserId);
            userEntity.setUserRegtime(new Date());
            userMapper.insert(userEntity);
        }

        //获取邀请人信息
        String recommenderWord = talent.getRecommenderWord();
        if(StringUtils.isNotBlank(recommenderWord)){
            if(talent.getWord().equals(talent.getRecommenderWord())){
                talent.setRecommenderWord(null);
            }else{
                String userid = bzTalentMapper.getByWord(recommenderWord);
                if(StringUtils.isNotBlank(userid)){
                    talent.setParentUserid(userid);
                }else{
                    talent.setRecommenderWord(null);
                }
            }
        }else{
            talent.setRecommenderWord(null);
        }

        save(talent);

        talent.setDsort(talent.getId());
        bzTalentMapper.updateBySort(talent);
    }


    @Override
    public void adduserInfoNew(BzTalent talent) {

        String userId = IdUtil.simpleUUID();
        Date now = new Date();
        talent.setRegTime(now);
        talent.setUpdateTime(now);
        talent.setStatus(1);
        talent.setPic(talent.getAvatarUrl());
        talent.setUserid(userId);

        User userEntity = new User();
        userEntity.setUserMobile(talent.getPhone());
        userEntity.setNickName(talent.getNickname());
        userEntity.setPic(talent.getPic());
        userEntity.setStatus(1);
        userEntity.setModifyTime(now);
        userEntity.setUserRegtime(now);
        userEntity.setUserId(userId);
        //设置密码
//        String password = EncryptionUtil.combinationEncryp(Constant.PASSWORD);
//        userEntity.setLoginPassword(password);

        String password = EncryptionUtil.combinationEncryp(talent.getLoginPassword());
        userEntity.setLoginPassword(password);
        userMapper.insert(userEntity);

        //获取邀请人信息
        String recommenderWord = talent.getRecommenderWord();
        if(StringUtils.isNotBlank(recommenderWord)){
            if(talent.getWord().equals(talent.getRecommenderWord())){
                talent.setRecommenderWord(null);
            }else{
                String userid = bzTalentMapper.getByWord(recommenderWord);
                if(StringUtils.isNotBlank(userid)){
                    talent.setParentUserid(userid);
                }else{
                    talent.setRecommenderWord(null);
                }
            }
        }else{
            talent.setRecommenderWord(null);
        }

        save(talent);
        talent.setDsort(talent.getId());
        bzTalentMapper.updateBySort(talent);
    }

    @Override
    public TalentVo selectByWord(TalentVo talentVo) {
        return bzTalentMapper.selectByWord(talentVo);
    }

    @Override
    public BzTalent selectByUserId(String userId) {
        BzTalent bzTalent = bzTalentMapper.selectOne(new LambdaQueryWrapper<BzTalent>()
                .eq(BzTalent::getUserid, userId)
                .select(BzTalent::getNickname, BzTalent::getWord, BzTalent::getId, BzTalent::getPic));
        return bzTalent;
    }


}
